package org.misty.seckill.service.impl;

import org.misty.seckill.exception.AuthorizationException;
import org.misty.seckill.model.User;
import org.misty.seckill.redis.RedisService;
import org.misty.seckill.redis.SessionKey;
import org.misty.seckill.service.LoginService;
import org.misty.seckill.service.UserService;
import org.misty.seckill.util.MD5Util;
import org.misty.seckill.util.UUIDUtil;
import org.misty.seckill.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

@Service
public class LoginServiceImpl implements LoginService {
  @Autowired
  private UserService userService;

  @Autowired
  private RedisService redisService;

  @Override
  public LoginVo login(LoginVo vo) {
    if (vo == null) {
      throw new AuthorizationException("缺少参数");
    }
    var id = Long.parseLong(vo.getMobile());
    var user = userService.getById(id);
    if (user == null) {
      throw new AuthorizationException("用户不存在: " + id);
    }
    var pass = MD5Util.formToDbPass(vo.getPassword(), user.getSalt());
    if (!pass.equals(user.getPassword())) {
      throw new AuthorizationException("密码错误");
    }
    var token = UUIDUtil.uuid();
    keepAlive(token, user);
    vo.setSessionToken(token);
    vo.setSessionExpiry(SessionKey.TOKEN.getExpiryInSec());
    return vo;
  }

  @Override
  public User getByToken(String token) {
    if (StringUtils.isEmpty(token)) {
      return null;
    }
    return redisService.get(SessionKey.TOKEN, token, User.class);
  }

  @Override
  public boolean keepAlive(String token, User user) {
    if (!StringUtils.isEmpty(token) && user != null) {
      return redisService.set(SessionKey.TOKEN, token, user);
    }
    return false;
  }

  @Override
  public String cacheRedirect(String token, String url) {
    if (StringUtils.isEmpty(url)) {
      return null;
    }
    if (StringUtils.isEmpty(token)) {
      token = UUIDUtil.uuid();
    }
    redisService.set(SessionKey.REDIRECT, token, url);
    return token;
  }

  @Override
  public boolean clearRedirect(String token) {
    if (!StringUtils.isEmpty(token)) {
      return redisService.del(SessionKey.REDIRECT, token);
    }
    return false;
  }

  @Override
  public String getRedirectByToken(String token) {
    if (StringUtils.isEmpty(token)) {
      return null;
    }
    return redisService.get(SessionKey.REDIRECT, token);
  }
}
